import { FC, useEffect, useRef, useState } from "react"
import Taro from '@tarojs/taro'
import arrow from '../../resource/arrow-bottom2.png';
import style from './style.less'
import { Picker } from "@tarojs/components";
import { EChart } from "taro3-echarts-react";

const Chart: FC = () => {
  const selector = ['上海', '苏州', '无锡', '常州']
  const [start, setStart] = useState('上海')
  const [end, setEnd] = useState('苏州')

  const [flag, setFlag] = useState(0)

  const handleChange = (e, num) => {
    console.log(e.detail.value);
    setFlag(0)
    if (num === 1) {
      setStart(selector[e.detail.value])
    } else {
      setEnd(selector[e.detail.value])
    }
  }

  const refBarChart = useRef<any>()
  const refLineChart = useRef<any>()

  useEffect(() => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://139.9.123.88:8082/fta-cargo/predict/predictCargo',
      method: 'POST',
      data: JSON.stringify({
        startCity: start,
        endCity: end,
      }),
      success: (data) => {
        console.log('预测数据', data);
        Taro.hideLoading()
        drawTodayChart(data.data.dayPredictCargo.hours, data.data.dayPredictCargo.cargoNum, data.data.dayPredictCargo.cargoAvgPrice)
        drawWeekChart(data.data.weekPredictCargo.cargoNum)
      },
      fail: () => {
        console.log('预测失败');
        Taro.hideLoading()
        const hours: string[] = []
        const cargoNum: number[] = []
        const cargoAvgPrice: number[] = []
        const weekCargoNum: number[] = []
        for (let i = 0; i < 24; i++) {
          hours.push(`今日${i}时`)
          cargoNum.push(Math.random() * 200 + 100)
          cargoAvgPrice.push(Math.random() * 100 + 200)
        }
        for (let j = 0; j < 7; j++) {
          weekCargoNum.push(Math.random() * 200 + 100)
        }
        drawTodayChart(hours, cargoNum, cargoAvgPrice)
        drawWeekChart(weekCargoNum)
      }
    })
  }, [start, end])

  const drawTodayChart = (hours, cargoNum, cargoAvgPrice) => {
    const option1 = {
      dataZoom: [{
        type: 'inside', //1平移 缩放
        throttle: '50', //设置触发视图刷新的频率。单位为毫秒（ms）。
        minValueSpan: 11, //用于限制窗口大小的最小值,在类目轴上可以设置为 5 表示 5 个类目
        start: 0, //数据窗口范围的起始百分比 范围是：0 ~ 100。表示 0% ~ 100%。
        end: 34, //数据窗口范围的结束百分比。范围是：0 ~ 100。
        zoomLock: true, //如果设置为 true 则锁定选择区域的大小，也就是说，只能平移，不能缩放。
      }],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          crossStyle: {
            color: '#999'
          }
        },
        formatter: function (arg) {
          return arg[0].name
        }
      },
      legend: {
        y: '30px',
        // 需要与series中的name保持一致
        data: ['发货量', '价格']
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          // 间隔多少个显示一个标签
          interval: 0,
          // 倾斜角度，避免重叠
          rotate: 40,
          // 字体颜色
          textStyle: {
            color: '#999',
          },
          // 字体大小
          fontSize: 9
        },
        data: hours
      },
      yAxis: [
        {
          type: 'value',
          // name: 'quantity',
          // 取消坐标值
          axisLabel: {
            show: false
          },
          // 取消刻度线
          axisTick: {
            show: false
          }
        },
        {
          type: 'value',
          // name: 'price',
          // 取消坐标值
          axisLabel: {
            show: false
          },
          // 取消刻度线
          axisTick: {
            show: false
          }
        },
      ],
      series: [
        {
          name: '发货量',
          data: cargoNum,
          type: 'bar',
          // 设置系列颜色
          color: '#5087ec'
        },
        {
          name: '价格',
          type: 'line',
          yAxisIndex: 1,
          data: cargoAvgPrice,
          color: '#68bbc4'
        }
      ]
    };
    refBarChart.current.refresh(option1);
  }

  const drawWeekChart = (cargoNum) => {
    const option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        formatter: function (arg) {
          return arg[0].name
        }
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          textStyle: {
            color: '#999',
          },
        },
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周天']
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          show: false
        },
        axisTick: {
          show: false
        }
      },
      series: [
        {
          data: cargoNum,
          type: 'line',
          smooth: true,
        }
      ],
    };
    refLineChart.current.refresh(option);
  }

  return (
    <div className={style.root}>
      <div className="header">
        <div className="title">近期货源热力图参考</div>
        <div className="container">
          <Picker mode='selector' range={selector} onChange={(e) => { handleChange(e, 1) }} onCancel={() => { setFlag(0) }}>
            <div onClick={() => { setFlag(1) }}>发货地：{start}
              <img className={flag === 1 ? 'active' : ''} src={arrow} alt="" />
            </div>
          </Picker>
          <Picker mode='selector' range={selector} onChange={(e) => { handleChange(e, 2) }} onCancel={() => { setFlag(0) }}>
            <div onClick={() => { setFlag(2) }} style={{ marginLeft: Taro.pxTransform(38) }}>卸货地：{end}
              <img className={flag === 2 ? 'active' : ''} src={arrow} alt="" />
            </div>
          </Picker>
        </div>
      </div>
      <div className='chart cha1' >
        <div className="cha1-title">今日发货量、价格预测</div>
        <EChart ref={refBarChart} canvasId='bar-chart' />
      </div>
      <div className='chart cha2'>
        <div className="cha2-title">本周发货量预测</div>
        <EChart ref={refLineChart} canvasId='line-chart' />
      </div>
    </div>
  )
}

export default Chart